# Semi-manual registration for Vanilla
# by Cee Pee

from deps.Form import Form
from deps.PageRequest import PageRequest
import forumapi
import sys
import os
import urllib.parse

class RegistrationException(Exception):
	"""Indicates an internal problem."""

class RegistrationError(RegistrationException):
	"""Indicates a server-side error during the registration process."""

class StopRegistration(RegistrationException):
	"""Indicates a client-side error during the registration process."""

class Registration(object):
	"""Handles the registration of a new account."""
	
	def __init__(self, site, args):
		self.site = site
		
		# Guest session
		self.session = forumapi.Session(self.site)
		
		self.name = args["name"]
		self.password = args["password"]
		self.email = args["email"]
		
		# Cloak user agent (is this bad?)
		forumapi.PageRequest.user_agent = "Mozilla/5.0 (Linux; U; en-US; rv:1.9.0.7) Firefox/3.0.7"
		
		# Send referers
		forumapi.PageRequest.send_referer = True
		
		self.show_rules = args["show_rules"]
	
	def accept_rules(self):
		if self.show_rules:
			page = self.session.get_page("termsofservice.php")
			page_soup = self.sesion.soup(page)
			
			rules = page_soup.findAll("p")
			for rule in rules:
				print(forumapi.remove_tags(rule))
			
			answer = input("Do you agree to these rules? (Y/N) ")
			if answer is not "Y":
				raise(StopRegistration("Registration halted by user."))
		
		return(True)
	
	def prepare_data(self, unused):
		page = self.session.get_page("people.php?PostBackAction=ApplyForm")
		page_soup = self.session.soup(page)
		
		form_soup = page_soup.find("form")
		form_data = Form(form_soup, session=self.session)
		
		form_data["Email"] = self.email
		form_data["Name"] = self.name
		form_data["NewPassword"] = self.password
		form_data["ConfirmPassword"] = self.password
		form_data["AgreeToTerms"] = "1"
		
		return(form_data)
	
	def register(self, form_data):
		page = form_data.submit()
